<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\hotel\controller;

use cmf\controller\HomeBaseController;
use app\hotel\model\HotelCateModel;
use app\hotel\model\HotelConfModel;
use app\hotel\model\HotelSystermModel;
use app\hotel\model\ReserveModel;
use app\hotel\model\ReservedetailModel;
use FontLib\Table\Type\name;
use think\Db;

class ListController extends HomeBaseController
{
    /***
     *  房型列表页
     */
    public function index()
    {

        $portalCategoryModel = new HotelCateModel();
        $list = $portalCategoryModel->where('delete_time', 0)->where('status', 1)->select();

        $this->assign('list', $list);

        return $this->fetch(':list');
    }

    /**
     * 房间详细
     */

    public function details()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id > 0) {
            $category = HotelCateModel::get($id)->toArray();
            $hotelCateModel = new HotelCateModel();
            $category['conf'] = json_decode($category['conf']);

            if(!empty($category['conf'])){
                $category['conf']  =implode(',',$category['conf']);
            }

            $list = $hotelCateModel->where('delete_time', 0)->where('id','<>',$id)->limit(3)->select();

            $this->assign('list', $list);

            $this->assign($category);


            $hotelConfModel = new HotelConfModel();
            $conf = $hotelConfModel->order("id ASC")
                ->where(array('status'=>'1'))
                ->select();
            return $this->fetch(':details');
        } else {
            $this->error('操作错误!');
        }

    }
    /**
     * 订单页面
     */

    public function order()
    {
        $HotelSysterm = new HotelSystermModel();
        $systerminfo            = $HotelSysterm->where('id', '1')->find();
        $this->assign('systerminfo', $systerminfo);
        return $this->fetch(':order');
    }
    /**
     * 订单完成页面
     */

    public function online()
    {
        return $this->fetch(':online');
    }

    /**
     * 订单添加逻辑
     */

    public function orderPost()
    {


        $arrData = $this->request->param();
        $openid = session('openid');
        if(!$openid){
            $this->auth();
        }

        $uid = Db::name('third_party_user')->where(['openid'=>$openid])->column('id');//用户id
$phone = '13146646176';
dump($uid);
        //订单数据
        $data = [

            'name'=>'谢方方',
            'tel'=>trim($phone),
            'user_id'=>$uid['0'],
            'room_id'=>14,
            'room_num'=>12,
            'checkin_time'=>'2018-06-05 00:00:00',
            'departure_time'=>'2018-06-09 12:00:00',
            'remark'=>'不需要',
            'price'=>'2000.00',
            'order_num'=>$this->getordnum(),
            'create_time'=>time(),
        ];
        $result = $this->validate($data, 'Reserve');
        if ($result !== true) {
            $res['code'] = '101';
            $res['mes'] = $result;
          /*  $this->error($result);*/
        }
        $ReserveModel = new ReserveModel();
        $ressult =  $ReserveModel->isUpdate(false)->allowField(true)->save($data);
        if ($ressult) {
            $res['code'] = '200';
            $res['mes'] = '提交成功';
            $res['data'] = ['ordernum'=>$data['order_num']];
            return json_encode($res);
        }else{
             $res['code'] = '101';
             $res['mes'] = $ressult;
               /* $this->error($result);*/
         return json_encode($res);
        }
        $this->success('保存成功');
      //  dump($ordnum);
    }


    //支付成功修改状态，减少库存

    public function goPay()
    {

        $arrData = $this->request->param();
        $openid = session('openid');
        $order_num = '2018060810298991';
        if(!$openid){
            $this->auth();
        }
        $uid = Db::name('third_party_user')->where(['openid'=>$openid])->column('id');//用户id

        $ReserveModel = new ReserveModel();
        $oserdata = $ReserveModel->where(['user_id'=>$uid['0'],'order_num'=>$order_num])->find();//订单详情
        if($oserdata['status'] == 1){

            $res = [
                'code'=>101,
                'mes'=>'此订单已经支付，请勿重复提交',
            ];
            return json_encode($res);

        }
        $ReservedetailModel = new ReservedetailModel();
        //订单详情
        $data = [
            'user_id'=>$uid['0'],
            'room_id'=>$oserdata['room_id'],
            'room_num'=>$oserdata['room_num'],
            'order_num'=>$oserdata['order_num'],
            'checkin_time'=>$oserdata['checkin_time'],
            'departure_time'=>$oserdata['departure_time'],
            'create_time'=>time(),
        ];
        // 启动事务
        Db::startTrans();
        try{
            //支付成功之后修改状态
            $ReserveModel->isUpdate(true)->save(["status" => '1'], ["order_num" => $order_num]);
            $ReservedetailModel->isUpdate(false)->allowField(true)->save($data);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        $res = [
             'code'=>200,
             'mes'=>'支付成功',
            ];
        return json_encode($res);
     }


    //检车库存
    public function checkH()
    {

        $room_number = 1;//预订数量
        $start_time = strtotime('2018-06-09 11:00:00');//入住时间
        $end_time   = strtotime('2018-06-12 12:00:00');//离店时间
        $room_id   = '13';//房间类型

        //根据id获取房间类型

        $portalCategoryModel = new HotelCateModel();
        $list = $portalCategoryModel->where('id', $room_id)->where('delete_time', 0)->where('status', 1)->field('name,number')->find();
        $room_num = $list['number'];//总库存

        $ReservedetailModel = new ReservedetailModel();

        $redislist =  $ReservedetailModel->where(['room_id'=>$room_id])->select();

        $redisnum = 0;//已经预定的数量
        foreach($redislist as $k=> $v){
          $res =   $this->is_time_cross(strtotime($v['checkin_time']),strtotime($v['departure_time']),$start_time,$end_time);
          if($res){
              $redisnum += $v['room_num'] ;
          }
        }
        $shengyu = $room_num - $redisnum;
          if($shengyu < $room_number ){ //查看是否预定完
              $res['code'] = 101;
              $res['mes'] ='对不起，您预定的房间现在已满！请试试别的房型';
              return json_encode($res);
          }
         return true;

    }


    /**
     * PHP计算两个时间段是否有交集（边界重叠不算）
     *
     * @param string $beginTime1 开始时间1
     * @param string $endTime1 结束时间1
     * @param string $beginTime2 开始时间2
     * @param string $endTime2 结束时间2
     * @return bool
     * @author blog.snsgou.com
     */
    function is_time_cross($beginTime1 = '', $endTime1 = '', $beginTime2 = '', $endTime2 = '')
    {
        $status = $beginTime2 - $beginTime1;
        if ($status > 0)
        {
            $status2 = $beginTime2 - $endTime1;
            if ($status2 >= 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        else
        {
            $status2 = $endTime2 - $beginTime1;
            if ($status2 > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
     /*获取订单编号*/
      function getordnum(){
         return    $ordnum = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        }

}
